import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Layout, Button, Card, Spin, Empty, message, Tag, Space, Modal, Input, Select, ConfigProvider, App } from 'antd';
import { PlusOutlined, EyeOutlined, EyeInvisibleOutlined, EditOutlined, DeleteOutlined, EditFilled, ThunderboltOutlined, SettingOutlined } from '@ant-design/icons';
import { chapterAPI, modelAPI } from '../../api/api';
import { useConfirm } from '../../hooks/useConfirm';
import { useDialog } from '../../hooks/useDialog';
import { Confirm } from '../../components/Confirm';
import { Dialog } from '../../components/Dialog';
import AdminNav from '../../components/AdminNav';
import './AdminHomeV2.css';

const { Sider, Content } = Layout;

function AdminHomeV2Content() {
  const { confirmState, showConfirm } = useConfirm();
  const { dialogState, showDialog } = useDialog();
  const [chapters, setChapters] = useState([]);
  const [chaptersWithModels, setChaptersWithModels] = useState([]);
  const [expandedChapters, setExpandedChapters] = useState(new Set());
  const [selectedModelId, setSelectedModelId] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [showAddModal, setShowAddModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [newChapter, setNewChapter] = useState({ title: '' });
  const [editingChapter, setEditingChapter] = useState(null);
  const [showCreateModelModal, setShowCreateModelModal] = useState(null);
  const [selectedDevice, setSelectedDevice] = useState('iphone-14-pro-max');
  const [zoomLevel, setZoomLevel] = useState(100);
  const navigate = useNavigate();

  // 设备型号预设（横屏尺寸）
  const devicePresets = {
    'iphone-14-pro-max': { name: 'iPhone 14 Pro Max', width: 926, height: 428, safeAreaLeft: 90 },
    'iphone-14-pro': { name: 'iPhone 14 Pro', width: 852, height: 393, safeAreaLeft: 85 },
    'iphone-14': { name: 'iPhone 14', width: 844, height: 390, safeAreaLeft: 80 },
    'iphone-13-pro-max': { name: 'iPhone 13 Pro Max', width: 926, height: 428, safeAreaLeft: 75 },
    'iphone-se': { name: 'iPhone SE', width: 667, height: 375, safeAreaLeft: 70 },
  };

  const loadChapters = async () => {
    try {
      setLoading(true);
      const data = await chapterAPI.getAll(true);
      setChapters(data);
      
      const chaptersWithModelsData = await Promise.all(
        data.map(async (chapter) => {
          try {
            const models = await modelAPI.getAll(chapter.id, true);
            return { ...chapter, models };
          } catch (err) {
            console.error(`加载章节 ${chapter.id} 的模型失败:`, err);
            return { ...chapter, models: [] };
          }
        })
      );
      
      setChaptersWithModels(chaptersWithModelsData);
      setError(null);
    } catch (err) {
      setError('加载章节失败: ' + err.message);
      message.error('加载章节失败: ' + err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadChapters();
  }, []);

  const handleAddChapter = async () => {
    if (!newChapter.title.trim()) {
      message.warning('请输入章节标题');
      return;
    }

    try {
      const maxOrder = chapters.length > 0 ? Math.max(...chapters.map(c => c.order_num)) : 0;
      await chapterAPI.create({
        ...newChapter,
        order_num: maxOrder + 1
      });
      setShowAddModal(false);
      setNewChapter({ title: '' });
      message.success('创建成功');
      loadChapters();
    } catch (err) {
      message.error('创建章节失败: ' + err.message);
    }
  };

  const handleEditChapter = async () => {
    if (!editingChapter?.title?.trim()) {
      message.warning('请输入章节标题');
      return;
    }

    try {
      await chapterAPI.update(editingChapter.id, {
        title: editingChapter.title,
        description: editingChapter.description
      });
      setShowEditModal(false);
      setEditingChapter(null);
      message.success('更新成功');
      loadChapters();
    } catch (err) {
      message.error('更新章节失败: ' + err.message);
    }
  };

  const handleDeleteChapter = async (id, title) => {
    const confirmed = await showConfirm({
      title: '确认删除',
      message: `确定要删除章节"${title}"吗？这将删除该章节下的所有模型。`,
      type: 'danger',
      confirmText: '删除',
      cancelText: '取消'
    });
    
    if (!confirmed) return;
    
    try {
      await chapterAPI.delete(id);
      message.success('删除成功');
      loadChapters();
    } catch (err) {
      message.error('删除章节失败: ' + err.message);
    }
  };

  const handleToggleHidden = async (id, currentHidden) => {
    try {
      await chapterAPI.update(id, { is_hidden: !currentHidden });
      // 只更新本地状态，避免重新加载
      setChapters(prev => prev.map(chapter =>
        chapter.id === id ? { ...chapter, is_hidden: !currentHidden } : chapter
      ));
      setChaptersWithModels(prev => prev.map(chapter =>
        chapter.id === id ? { ...chapter, is_hidden: !currentHidden } : chapter
      ));
      message.success('操作成功');
    } catch (err) {
      message.error('切换章节状态失败: ' + err.message);
    }
  };

  const handleModelToggleHidden = async (modelId, currentHidden, isSpecial) => {
    try {
      // 特殊模型使用专门的API
      if (isSpecial) {
        await modelAPI.updateSpecialHidden(modelId, !currentHidden);
      } else {
        await modelAPI.update(modelId, { is_hidden: !currentHidden });
      }
      // 只更新本地状态，避免重新加载
      setChaptersWithModels(prev => prev.map(chapter => ({
        ...chapter,
        models: chapter.models.map(model =>
          model.id === modelId ? { ...model, is_hidden: !currentHidden } : model
        )
      })));
      message.success('操作成功');
    } catch (err) {
      message.error('切换模型状态失败: ' + err.message);
    }
  };

  const handleModelEdit = async (model) => {
    // 特殊模型只能编辑标题
    if (model.is_special) {
      const result = await showDialog({
        title: '编辑特殊模型',
        fields: [
          {
            name: 'title',
            label: '模型标题',
            type: 'text',
            defaultValue: model.title,
            required: true
          }
        ],
        confirmText: '保存',
        cancelText: '取消'
      });

      if (!result) return;

      try {
        await modelAPI.update(model.id, { title: result.title });
        message.success('模型标题已更新');
        loadChapters();
      } catch (error) {
        message.error('更新失败: ' + error.message);
      }
    } else {
      // 普通模型跳转到工作空间编辑
      navigate(`/admin/workspace/${model.id}`);
    }
  };

  const handleModelDelete = async (modelId, title, isSpecial) => {
    const confirmed = await showConfirm({
      title: '确认删除',
      message: `确定要删除模型"${title}"吗？`,
      type: 'danger',
      confirmText: '删除',
      cancelText: '取消'
    });
    
    if (!confirmed) return;
    
    try {
      if (isSpecial) {
        await modelAPI.deleteSpecial(modelId);
      } else {
        await modelAPI.delete(modelId);
      }
      message.success('删除成功');
      if (selectedModelId === modelId) {
        setSelectedModelId(null);
      }
      // 只更新本地状态，避免重新加载
      setChaptersWithModels(prev => prev.map(chapter => ({
        ...chapter,
        models: chapter.models.filter(model => model.id !== modelId)
      })));
    } catch (err) {
      message.error('删除模型失败: ' + err.message);
    }
  };

  const handleModelUpdateTemplate = async (modelId, currentTemplate) => {
    const result = await showDialog({
      title: '修改模板路径',
      message: '请输入新的模板路径',
      fields: [
        {
          name: 'template_path',
          label: '模板路径',
          type: 'text',
          placeholder: '例如: TriangleHeight',
          defaultValue: currentTemplate || '',
          required: true
        }
      ],
      confirmText: '确认',
      cancelText: '取消'
    });
    
    if (result && result.template_path) {
      updateTemplatePath(modelId, result.template_path);
    }
  };

  const updateTemplatePath = async (modelId, newTemplate) => {
    try {
      await modelAPI.updateTemplate(modelId, newTemplate);
      message.success('模板路径更新成功');
      // 只更新本地状态，避免重新加载
      setChaptersWithModels(prev => prev.map(chapter => ({
        ...chapter,
        models: chapter.models.map(model =>
          model.id === modelId ? { ...model, template_path: newTemplate } : model
        )
      })));
    } catch (err) {
      message.error('更新模板路径失败: ' + err.message);
    }
  };

  const handleModelReorder = async (chapterId, dragIndex, dropIndex) => {
    try {
      // 找到对应的章节
      const chapter = chaptersWithModels.find(c => c.id === chapterId);
      if (!chapter || !chapter.models) return;

      // 创建新的模型数组
      const newModels = [...chapter.models];
      const [draggedItem] = newModels.splice(dragIndex, 1);
      newModels.splice(dropIndex, 0, draggedItem);

      // 立即更新本地状态以提供即时反馈
      setChaptersWithModels(prev => prev.map(c =>
        c.id === chapterId ? { ...c, models: newModels } : c
      ));

      // 批量更新所有模型的 order_num
      const updatePromises = newModels.map((model, index) =>
        modelAPI.update(model.id, { order_num: index + 1 })
      );

      await Promise.all(updatePromises);
      message.success('模型顺序更新成功');
    } catch (err) {
      message.error('更新模型顺序失败: ' + err.message);
      // 失败时重新加载数据
      loadChapters();
    }
  };

  if (loading) {
    return (
      <div className="admin-home-v2">
        <AdminNav />
        <div className="loading-container">
          <Spin size="large">
            <div style={{ paddingTop: 50 }}>加载中...</div>
          </Spin>
        </div>
      </div>
    );
  }

  return (
    <div className="admin-home-v2">
        <AdminNav />
        <Layout className="admin-layout-v2">
        <Sider width={320} className="admin-sider">
          <div className="sider-header">
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              block
              onClick={() => setShowAddModal(true)}
            >
              新建章节
            </Button>
          </div>
          <div className="sider-content">
            {error && (
              <div className="error-banner">
                {error}
              </div>
            )}
            {chapters.length === 0 ? (
              <Empty description="暂无章节" />
            ) : (
              <ChapterList
                chapters={chaptersWithModels}
                expandedChapters={expandedChapters}
                onToggleChapter={(id) => {
                  const newExpanded = new Set(expandedChapters);
                  if (newExpanded.has(id)) {
                    newExpanded.delete(id);
                  } else {
                    newExpanded.add(id);
                  }
                  setExpandedChapters(newExpanded);
                }}
                onSelectModel={setSelectedModelId}
                selectedModelId={selectedModelId}
                onEdit={(chapter) => {
                  setEditingChapter(chapter);
                  setShowEditModal(true);
                }}
                onDelete={handleDeleteChapter}
                onToggleHidden={handleToggleHidden}
                onModelEdit={handleModelEdit}
                onModelDelete={handleModelDelete}
                onModelToggleHidden={handleModelToggleHidden}
                onModelUpdateTemplate={handleModelUpdateTemplate}
                onCreateModel={(chapterId) => setShowCreateModelModal(chapterId)}
                onModelReorder={handleModelReorder}
              />
            )}
          </div>
        </Sider>
        <Content className="admin-content">
          {selectedModelId ? (
            <div className="preview-container">
              <div className="preview-header">
                <Select
                  value={selectedDevice}
                  onChange={setSelectedDevice}
                  style={{ width: 200 }}
                  options={Object.entries(devicePresets).map(([key, preset]) => ({
                    label: preset.name,
                    value: key
                  }))}
                />
                <span className="device-size">
                  {devicePresets[selectedDevice].width} × {devicePresets[selectedDevice].height}
                </span>
                <div className="zoom-controls">
                  {[100, 125, 150, 175].map(zoom => (
                    <Button
                      key={zoom}
                      type={zoomLevel === zoom ? 'primary' : 'default'}
                      size="small"
                      onClick={() => setZoomLevel(zoom)}
                    >
                      {zoom}%
                    </Button>
                  ))}
                </div>
              </div>
              <div 
                className="iframe-wrapper"
                style={{
                  width: `${devicePresets[selectedDevice].width}px`,
                  height: `${devicePresets[selectedDevice].height}px`,
                  transform: `scale(${zoomLevel / 100})`,
                  transformOrigin: 'top center',
                  position: 'relative',
                  background: '#000'
                }}
              >
                {devicePresets[selectedDevice].safeAreaLeft > 0 && (
                  <div
                    className="safe-area-overlay"
                    style={{
                      position: 'absolute',
                      left: 0,
                      top: 0,
                      width: `${devicePresets[selectedDevice].safeAreaLeft}px`,
                      height: '100%',
                      background: 'rgba(0, 0, 0, 0.8)',
                      borderRight: '2px solid rgba(255, 0, 0, 0.6)',
                      zIndex: 10,
                      pointerEvents: 'none'
                    }}
                  >
                    <div style={{
                      position: 'absolute',
                      top: '50%',
                      left: '50%',
                      transform: 'translate(-50%, -50%) rotate(-90deg)',
                      color: 'rgba(255, 255, 255, 0.5)',
                      fontSize: '11px',
                      fontWeight: 'bold',
                      whiteSpace: 'nowrap'
                    }}>
                      不可渲染区域
                    </div>
                  </div>
                )}
                <iframe
                  src={`/geometry/model/${selectedModelId}`}
                  className="model-preview-iframe"
                  title="模型预览"
                  style={{
                    position: 'absolute',
                    left: `${devicePresets[selectedDevice].safeAreaLeft}px`,
                    top: 0,
                    width: `${devicePresets[selectedDevice].width - devicePresets[selectedDevice].safeAreaLeft}px`,
                    height: '100%'
                  }}
                />
              </div>
            </div>
          ) : (
            <Empty description="请从左侧选择一个模型进行预览" />
          )}
        </Content>
      </Layout>

      <Modal
        title="新建章节"
        open={showAddModal}
        onOk={handleAddChapter}
        onCancel={() => {
          setShowAddModal(false);
          setNewChapter({ title: '' });
        }}
        okText="创建"
        cancelText="取消"
      >
        <Input
          placeholder="请输入章节标题"
          value={newChapter.title}
          onChange={(e) => setNewChapter({ ...newChapter, title: e.target.value })}
          onPressEnter={handleAddChapter}
          autoFocus
        />
      </Modal>

      <Modal
        title="编辑章节"
        open={showEditModal}
        onOk={handleEditChapter}
        onCancel={() => {
          setShowEditModal(false);
          setEditingChapter(null);
        }}
        okText="保存"
        cancelText="取消"
      >
        <Input
          placeholder="请输入章节标题"
          value={editingChapter?.title || ''}
          onChange={(e) => setEditingChapter({ ...editingChapter, title: e.target.value })}
          onPressEnter={handleEditChapter}
          autoFocus
        />
      </Modal>

      <Modal
        title="选择模型类型"
        open={!!showCreateModelModal}
        onCancel={() => setShowCreateModelModal(null)}
        footer={null}
        width={600}
      >
        <div className="model-type-grid">
          <Card
            hoverable
            className="model-type-card"
            onClick={() => {
              setShowCreateModelModal(null);
              navigate(`/admin/workspace?chapter_id=${showCreateModelModal}&type=normal`);
            }}
          >
            <div className="model-type-icon">
              <EditFilled style={{ fontSize: 32, color: '#1890ff' }} />
            </div>
            <h3>绘制模型</h3>
            <p>使用可视化工具绘制几何图形，添加点、线、标签等元素</p>
            <div className="model-type-features">
              <Tag>可视化绘制</Tag>
              <Tag>拖拽交互</Tag>
              <Tag>常量监控</Tag>
            </div>
          </Card>

          <Card
            hoverable
            className="model-type-card"
            onClick={() => {
              setShowCreateModelModal(null);
              navigate(`/admin/workspace?chapter_id=${showCreateModelModal}&type=special`);
            }}
          >
            <div className="model-type-icon">
              <ThunderboltOutlined style={{ fontSize: 32, color: '#722ed1' }} />
            </div>
            <h3>特殊模型</h3>
            <p>使用预定义模板创建高级交互式几何演示</p>
            <div className="model-type-features">
              <Tag color="purple">高级交互</Tag>
              <Tag color="purple">预定义模板</Tag>
              <Tag color="purple">丰富动画</Tag>
            </div>
          </Card>
        </div>
      </Modal>
      {confirmState && (
        <Confirm
          title={confirmState.title}
          message={confirmState.message}
          type={confirmState.type}
          confirmText={confirmState.confirmText}
          cancelText={confirmState.cancelText}
          onConfirm={confirmState.onConfirm}
          onCancel={confirmState.onCancel}
        />
      )}
      {dialogState && (
        <Dialog
          title={dialogState.title}
          message={dialogState.message}
          fields={dialogState.fields}
          confirmText={dialogState.confirmText}
          cancelText={dialogState.cancelText}
          onConfirm={dialogState.onConfirm}
          onCancel={dialogState.onCancel}
        />
      )}
      </div>
  );
}

function AdminHomeV2() {
  return (
    <ConfigProvider
      theme={{
        token: {
          colorPrimary: '#1890ff',
          colorLink: '#1890ff',
          borderRadius: 6,
        },
      }}
    >
      <App>
        <AdminHomeV2Content />
      </App>
    </ConfigProvider>
  );
}

function ChapterList({ chapters, onSelectModel, selectedModelId, onEdit, onDelete, onToggleHidden, onModelEdit, onModelDelete, onModelToggleHidden, onModelUpdateTemplate, onCreateModel, onModelReorder }) {
  const [draggedModel, setDraggedModel] = useState(null);
  const [draggedChapterId, setDraggedChapterId] = useState(null);

  return (
    <div className="chapter-list">
      {chapters.map((chapter) => (
        <Card
          key={chapter.id}
          size="small"
          className="chapter-card"
          title={
            <div className="chapter-title-wrapper">
              <span className="chapter-order">第 {chapter.order_num} 章</span>
              <span className="chapter-title-text">{chapter.title}</span>
              {chapter.is_hidden === 1 && (
                <Tag color="orange" icon={<EyeInvisibleOutlined />} size="small">
                  隐藏
                </Tag>
              )}
            </div>
          }
          extra={
            <Space>
              <Button
                type="text"
                size="small"
                icon={chapter.is_hidden ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                onClick={(e) => {
                  e.stopPropagation();
                  onToggleHidden(chapter.id, chapter.is_hidden);
                }}
                title={chapter.is_hidden ? "设为显示" : "设为隐藏"}
              />
              <Button
                type="text"
                size="small"
                icon={<EditOutlined />}
                onClick={(e) => {
                  e.stopPropagation();
                  onEdit(chapter);
                }}
                title="编辑"
              />
              <Button
                type="text"
                size="small"
                danger
                icon={<DeleteOutlined />}
                onClick={(e) => {
                  e.stopPropagation();
                  onDelete(chapter.id, chapter.title);
                }}
                title="删除"
              />
            </Space>
          }
        >
          <div className="model-list">
            <Button
              type="dashed"
              size="small"
              icon={<PlusOutlined />}
              block
              onClick={(e) => {
                e.stopPropagation();
                onCreateModel(chapter.id);
              }}
              style={{ marginBottom: 8 }}
            >
              新建模型
            </Button>
            {chapter.models?.map((model, index) => (
              <div
                key={model.id}
                className={`model-item ${selectedModelId === model.id ? 'active' : ''}`}
                draggable={true}
                onDragStart={(e) => {
                  setDraggedModel(index);
                  setDraggedChapterId(chapter.id);
                  e.currentTarget.style.opacity = '0.5';
                }}
                onDragEnd={(e) => {
                  e.currentTarget.style.opacity = '1';
                  setDraggedModel(null);
                  setDraggedChapterId(null);
                }}
                onDragOver={(e) => {
                  e.preventDefault();
                }}
                onDrop={(e) => {
                  e.preventDefault();
                  if (draggedModel !== null && draggedChapterId === chapter.id && draggedModel !== index) {
                    onModelReorder(chapter.id, draggedModel, index);
                  }
                }}
              >
                <span
                  className="model-item-title"
                  onClick={() => onSelectModel(model.id)}
                >
                  {model.is_hidden === 1 && <EyeInvisibleOutlined style={{ marginRight: 4, color: '#999' }} />}
                  {model.is_special === 1 && <Tag color="purple" size="small" style={{ marginRight: 4 }}>特殊</Tag>}
                  {model.title}
                </span>
                <Space className="model-item-actions">
                  <Button
                    type="text"
                    size="small"
                    icon={model.is_hidden ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                    onClick={(e) => {
                      e.stopPropagation();
                      onModelToggleHidden(model.id, model.is_hidden, model.is_special === 1);
                    }}
                    title={model.is_hidden ? "设为显示" : "设为隐藏"}
                  />
                  {model.is_special === 1 && (
                    <Button
                      type="text"
                      size="small"
                      icon={<SettingOutlined />}
                      onClick={(e) => {
                        e.stopPropagation();
                        onModelUpdateTemplate(model.id, model.template_path);
                      }}
                      title="换绑模板"
                    />
                  )}
                  <Button
                    type="text"
                    size="small"
                    icon={<EditOutlined />}
                    onClick={(e) => {
                      e.stopPropagation();
                      onModelEdit(model);
                    }}
                    title={model.is_special === 1 ? "编辑标题" : "编辑"}
                  />
                  <Button
                    type="text"
                    size="small"
                    danger
                    icon={<DeleteOutlined />}
                    onClick={(e) => {
                      e.stopPropagation();
                      onModelDelete(model.id, model.title, model.is_special === 1);
                    }}
                    title="删除"
                  />
                </Space>
              </div>
            ))}
            {chapter.models?.length === 0 && (
              <div className="empty-models">暂无模型</div>
            )}
          </div>
        </Card>
      ))}
    </div>
  );
}

export default AdminHomeV2;

